import DeviceTemplate from "@/components/DeviceTemplate";
import React, { useState } from 'react';
import { Text, View, TouchableOpacity, StyleSheet } from 'react-native';
import { useNavigation } from 'expo-router';
import { useAudioPlayer } from 'expo-audio';
import SpO2Parser from '../../utils/SpO2Parser';

const SpO2Device: React.FC = () => {
    const [showCompletionDialog, setShowCompletionDialog] = useState(false);
    const navigation = useNavigation();
    
    // 使用 useAudioPlayer hook 创建音频播放器
    const audioSource = require('../../assets/mp3/notice.mp3');
    const player = useAudioPlayer(audioSource);

    const playNotificationSound = () => {
        try {
            // 重置到开头并播放
            player.seekTo(0);
            player.play();
        } catch (error) {
            console.error('Error playing sound:', error);
        }
    };

    // 判断血氧检测是否完成
    const isSpO2TestComplete = (measurement: any): boolean => {
        if (!measurement || typeof measurement.value !== 'object') return false;
        // 血氧检测完成条件：有心率和血氧数据
        return measurement.value.heartRate > 0 && measurement.value.spo2 > 0;
    };

    const handleTestComplete = () => {
        // 显示检测完成提示对话框
        setShowCompletionDialog(true);
        // 播放完成提示音
        playNotificationSound();
    };

    const finishTest = () => {
        setShowCompletionDialog(false);
        navigation.goBack();
    };

    return (
        <>
            <DeviceTemplate
                deviceName="血氧检测仪"
                deviceNamePrefix="PC-60F"
                serviceUUID={SpO2Parser.SERVICE_UUID}
                dataCharacteristic={SpO2Parser.DATA_CHARACTERISTIC}
                parser={{
                    parseData: SpO2Parser.parseData
                }} 
                commandServiceUUID={undefined} 
                commandCharacteristic={undefined} 
                startCommand={''} 
                stopCommand={''}
                withResp={false}
                deviceRoute="SpO2"
                onTestComplete={handleTestComplete}
            >
                {/* 可以在这里添加血氧检测特定的UI元素 */}
            </DeviceTemplate>
            
            {/* 检测完成提示对话框 */}
            {showCompletionDialog && (
                <View style={styles.dialogOverlay}>
                    <View style={styles.dialogContainer}>
                        <Text style={styles.dialogTitle}>检测完成</Text>
                        <Text style={styles.dialogMessage}>您的检测已完成并已自动保存结果</Text>
                        <View style={styles.dialogButtons}>
                            <TouchableOpacity
                                style={[styles.dialogButton, styles.stayButton]}
                                onPress={() => setShowCompletionDialog(false)}
                            >
                                <Text style={styles.stayButtonText}>继续检测</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[styles.dialogButton, styles.returnButton]}
                                onPress={finishTest}
                            >
                                <Text style={styles.returnButtonText}>返回</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            )}
        </>
    );
};

const styles = StyleSheet.create({
    // 检测完成提示对话框样式
    dialogOverlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 1000,
    },
    dialogContainer: {
        backgroundColor: 'white',
        borderRadius: 12,
        padding: 24,
        width: '80%',
        maxWidth: 320,
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5,
    },
    dialogTitle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 16,
    },
    dialogMessage: {
        fontSize: 16,
        color: '#666',
        textAlign: 'center',
        marginBottom: 24,
    },
    dialogButtons: {
        flexDirection: 'row',
        width: '100%',
        justifyContent: 'space-between',
    },
    dialogButton: {
        flex: 1,
        paddingVertical: 12,
        paddingHorizontal: 16,
        borderRadius: 8,
        alignItems: 'center',
        marginHorizontal: 8,
    },
    stayButton: {
        backgroundColor: '#f0f0f0',
    },
    returnButton: {
        backgroundColor: '#0a7ea4',
    },
    stayButtonText: {
        fontSize: 16,
        color: '#333',
        fontWeight: 'bold',
    },
    returnButtonText: {
        fontSize: 16,
        color: 'white',
        fontWeight: 'bold',
    }
});

export default SpO2Device;
